<template>
  <div class="future-weather">
    <div>
      <p>
        <span>
          {{location.name}}
        </span>未来24小时天气
      </p>
    </div>
    <div class="container" ref="echartContainer"></div>
  </div> 
</template>
<script>
import axios from 'axios'
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';


echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from 'dayjs';
// 引入一些常量
import {KEY,API_24H} from "@/common/constrant";
export default{
  data(){
      return{
        hourly:[],
        hour24Data:{
          fxTime:[],
          temp:[]
        }
      }
  },
  computed:{
    location:function () {
      return this.$store.state.location
      
    }
  },
  created(){

  },
  methods:{
    //获取API数据
    getData(){
      axios.get(API_24H,{
        params:{
          location:this.location.id,
          key:KEY,
        }
      }).then((res)=>{
        console.log(res.data)
        this.hourly=res.data.hourly
        // console.log(this.hourly)
        //遍历hourly这个数组，从这个数组中分别取出fxTime,temp
        this.hour24Data.fxTime=[]
        this.hour24Data.temp=[]
        this.hourly.forEach(element => {
          this.hour24Data.fxTime.push(element.fxTime)
          this.hour24Data.temp.push(element.temp)
        });
        //调用初始化图表的方法
        this.initChart(
          this.hour24Data.fxTime.map(e=>dayjs(e).format("HH")),
          this.hour24Data.temp
        )
      });   
    },
     //初始化图表
  initChart(xAxisData,seriesData){
    // var chartDom = document.getElementById('main');
    var chartDom = this.$refs.echartContainer
    var myChart = echarts.init(chartDom);
    var option;

    option = {
      xAxis: {
        type: 'category',
        data: xAxisData,
      },
    yAxis: {
      type: 'value'
      },
    series:[
    {
      data: seriesData,
      type: 'line'
      }
    ]
};

option && myChart.setOption(option);

  }
  },
  mounted(){
    this.getData()
  },
  watch:{
    location:function(){
        this.getData();
    }
  }
    
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container{
  height: 20rem;

}
div>p>span{
  color:red;
}

</style>
